package com.qysoft.rapid.core;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Logger;
import com.qysoft.rapid.consts.RapidConsts;
import com.qysoft.rapid.exceptions.BizException;
import com.qysoft.rapid.exceptions.RapidException;
import com.qysoft.rapid.plugin.mybatis.MyBatisSessionManager;

/**
 * 平台数据库连接介入，用于非事务控制
 * @author liugong
 *
 */
public class RapidDbConn implements Interceptor {
	
	private final Logger log = Logger.getLogger(RapidDbConn.class);
	
	public void intercept(Invocation ai) {
		interceptForMyBatis(ai); 
	}
	
	
	/**
	 * 实现mybatis下的事务控制
	 * @param ai
	 */
	private void interceptForMyBatis(Invocation ai){
		MyBatisSessionManager.setSession(true); 
		doLog("RapidDbConn：已获取数据库连接...");
		try {
			doLog("RapidDbConn：准备执行业务...");
			ai.invoke();
			doLog("RapidDbConn：业务已执行...");
		}catch (BizException e){
			throw e;
		}catch (Exception e) {
			e.printStackTrace();
			throw new RapidException(e.getMessage());
		}finally{
			MyBatisSessionManager.closeSession();
			doLog("RapidDbConn：数据库 连接已释放...");
		}
	}
	
	private void doLog(String message){
		if (RapidConsts.isIS_DEV_MODE()) {
			log.warn(message);
		}
	}
	
}

